var WxParse = require('../../wxParse/wxParse.js');
// pages/detail/detail.js
import {
  goodInfo,
  userAddressList,
  shoppingCarAddModify,
  shoppingCarList
} from '../../api/api'
import {
  region
} from '../../api/region'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //已选规格的img
    sku_img: '',
    //已选规格的价格
    sku_price: 0,
    //存放要和选中的值进行匹配的数据
    shopItemInfo: {},
    //被选中的值
    selectArr: [],
    //被选中的值的索引
    subIndex: [],
    //上面是sku数据
    showSku: true,
    showAddress: true,
    //购买数量
    num: 1,
    //地址列表
    addressList: [],
    //选择的地址
    sureAddress: '',
    //判断是加入购物车还是立即购买
    click: 0,
    //顶部提示
    topType: 'success',
    topInfo: '',
    showTop: false
  },
  //获取购物车列表
  getCarList() {
    shoppingCarList({
      token: app.globalData.userInfo.token
    }).then(res => {
      console.log(res);
      this.setData({
        shopCarList: res.data.data
      })
    })
  },
  //点击确定 加入购物车 立即购买
  sure() {
    console.log(111);
    //加入购物车
    if (this.data.click == 1 || this.data.click == 0) {
      let shopCar = this.data.shopCarList
      let obj = {
        token: app.globalData.userInfo.token,
        good_id: this.data.goodInfo.good_id,
        num: this.data.num,
        price: Number(this.data.goodInfo.price),
        money: this.data.num * this.data.goodInfo.price,
        sku: JSON.stringify(this.data.shopItemInfo[this.data.selectArr])
      }
      let index = shopCar.findIndex(item => {
        return JSON.parse(item.sku).difference == this.data.shopItemInfo[this.data.selectArr].difference
      })
      if (index != -1) {
        obj.shopping_car_id = shopCar[index].shopping_car_id
        obj.num = Number(shopCar[index].num) + Number(this.data.num)
        obj.money = (Number(shopCar[index].num) + Number(this.data.num)) * Number(this.data.goodInfo.price)
      }
      shoppingCarAddModify(obj).then(res => {
        console.log(res);
        this.setData({
          showSku: true,
          topType: 'info',
          topInfo: '添加成功',
          showTop: true
        })
      })
    }
  },
  //数量减
  red() {
    if (this.data.num < 2) {
      return
    }
    this.setData({
      num: --this.data.num
    })
  },
  //数量加
  add() {
    this.setData({
      num: ++this.data.num
    })
  },
  //控制地址选择开关
  switch_address() {
    this.setData({
      showAddress: false
    })
  },
  //控制sku开关
  switch_sku(e) {
    this.setData({
      showSku: false,
      click: e.currentTarget.dataset.num
    })
  },
  //初始化可选数据
  initShopItemInfo() {
    let obj = {}
    for (const i in this.data.sku.goods) {
      obj[this.data.sku.goods[i].difference] = this.data.sku.goods[i]
    }
    this.setData({
      shopItemInfo: obj
    })
    console.log(this.data.shopItemInfo);
    this.checkItem()
  },
  //选择sku
  chooseSku(e) {
    let index = e.currentTarget.dataset.index
    let item = e.currentTarget.dataset.it
    let ind = e.currentTarget.dataset.ind
    let select_text = ''
    let subIndex = -1
    let select = `selectArr[${index}]`
    let sub = `subIndex[${index}]`
    if (item.isShow) {
      return
    }
    if (this.data.selectArr[index] != item.name) {
      select_text = item.name
      subIndex = ind
    }
    this.setData({
      [select]: select_text,
      [sub]: subIndex
    })
    this.checkItem()
  },
  checkItem() {
    let option = this.data.sku.option
    let result = this.data.selectArr
    for (const i in option) {
      let copy = result[i]
      for (const k in option[i].option) {
        result[i] = option[i].option[k].name
        option[i].option[k].isShow = this.canShow(result)
      }
      result[i] = copy
    }
    option.forEach((item, index) => {
      let ind = item.option.findIndex(i => i.name == this.data.selectArr[index])
      if (ind != -1) {
        item.option[ind].isShow = false
      }
    })
    let setOption = `sku.option`
    this.setData({
      [setOption]: option
    })
    let flag = 0
    result.forEach(item => {
      if (item != "") {
        flag++
      }
    })
    if (flag == option.length) {
      this.setData({
        sku_price: this.data.shopItemInfo[result].price,
        sku_img: this.data.shopItemInfo[result].src
      })
    }

  },
  canShow(result) {
    for (const i in result) {
      if (result[i] == "") {
        return false
      }
    }
    console.log(this.data.shopItemInfo[result]);
    return this.data.shopItemInfo[result].stock ? false : true
  },

  //获取信息
  detail(id) {
    goodInfo({
      good_id: id
    }).then(res => {
      res.data.info[0].info = JSON.parse(res.data.info[0].info)
      let item = JSON.parse(JSON.parse(res.data.info[0].edition))
      console.log(item);
      let length = item.option.length
      item.goods.forEach(item => {
        item.difference = Object.values(item).slice(0,length).join(',')
      })
      item.option.forEach(i => {
        for (const j in i.option) {
          i.option[j] = {
            name: i.option[j]
          }
        }
      })
      this.setData({
        goodInfo: res.data,
        sku: item
      })
      var that = this;
      var detail_content = this.data.goodInfo.info[0].info;
      WxParse.wxParse('detail_content', 'html', detail_content, that, 5);
      // console.log(this.data.sku);
      let newArr = []
      let subArr = []
      item.option.forEach(i => {
        let title = i.normsName
        for (const key in item.goods[0]) {
          if (key == title) {
            newArr.push(item.goods[0][key])
            let subIndex = i.option.findIndex(k => k == item.goods[0][key])
            subArr.push(subIndex)
          }
        }
      })
      this.setData({
        selectArr: newArr,
        subIndex: subArr
      })
      this.initShopItemInfo()
    })
  },
  //获取地址列表
  getAddress() {
    userAddressList({
      token: app.globalData.userInfo.token
    }).then(res => {
      res.data.forEach(item => {
        let procince = `${item.procince}0000`
        let city = `${item.procince}${item.city}00`
        let area = `${item.procince}${item.city}${item.area}`
        let index = region.findIndex(i => i.provinceCode == procince)
        let cIndex = region[index].mallCityList.findIndex(j => j.cityCode == city)
        let aIndex = region[index].mallCityList[cIndex].mallAreaList.findIndex(k => k.areaCode == area)
        item.procince_text = region[index].provinceName
        item.city_text = region[index].mallCityList[cIndex].cityName
        item.area_text = region[index].mallCityList[cIndex].mallAreaList[aIndex].areaName
      })
      this.setData({
        addressList: res.data,
        sureAddress: res.data[0]
      })
    })
  },
  //选择地址
  chooseAddress(e) {
    console.log(e);
    this.setData({
      sureAddress: this.data.addressList[e.currentTarget.dataset.index],
      showAddress: true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      info: JSON.parse(options.item)
    })
    console.log(this.data);
    this.detail(this.data.info.good_id)
    // this.detail(1576)
    this.getAddress()
    this.getCarList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})